<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-dialog :title="formData.id?'编辑角色':'添加角色'" :visible="showDialog" @close="closeFn">
        <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="title">
            <el-input v-model="formData.title" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeFn">取 消</el-button>
          <el-button type="primary" @click="confirmFn">确定</el-button>
        </div>
      </el-dialog>
    </div></div>
</template>
<script>
import { getRoleDetailById, editRole, addRole } from '@/api/role'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        description: '',
        id: '',
        permissions: ''
      },
      rules: {
        title: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /* 确定修改角色 */
    async confirmFn() {
      try {
        await this.$refs.form.validate()
        if (this.formData.id) {
          await editRole(this.formData)
          this.$message.success('修改角色成功')
        } else {
          await addRole(this.formData)
          this.$message.success('添加角色成功')
        }
        this.closeFn()
      } catch (error) {
        console.log(error)
      }
      /* 加了await之后才能触发promise 这样没有通过表单验证的话就不会调用接口*/
    },
    /* 关闭弹框 */
    closeFn() {
      this.$emit('update:showDialog', false)
      this.$refs.form.resetFields()
      /* 清空表单数据 */
      this.formData = {
        title: '',
        description: ''
      }
      /* 刷新列表 */
      this.$parent.getRoleLists()
    },
    /* 根据id获取当前角色详情 */
    async getRoleDetailById(id) {
      this.formData = await getRoleDetailById(id)
      // console.log( this.formData)
    }
  }
}
</script>

<style>

</style>
